#include "FileController.h"

#include <fstream>

FileController::FileController(const std::string &root_dir) : m_root_dir(root_dir)
{
}

FileController::~FileController()
{
}

void FileController::getImage(const httplib::Request &req, httplib::Response &res)
{
    std::string image_name = req.matches[1];
    std::string image_path = m_root_dir + image_name;

    std::ifstream ifs(image_path, std::ios::binary);
    if (ifs) {
        res.set_header("Content-Type", "image/jpeg");
        res.body   = std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
        res.status = 200;
    } else {
        res.status = 404;
    }
}

void FileController::bind(httplib::Server *server)
{
    server->Get("/image/(.+)", bindController(&FileController::getImage, this));
}